<?php

namespace Biz\service\brand;

use Biz\model\brandActivity\BlindBoxActivity as mBlindBoxActivity;
use Biz\model\brandActivity\BlindBoxActivityPrize as mBlindBoxActivityPrize;
use Biz\model\brandActivity\BlindBoxChangeRecord as mBlindBoxChangeRecord;
use Biz\model\brandActivity\BlindBoxCueCard as mBlindBoxCueCard;
use Biz\model\brandActivity\BlindBoxCueCardRecord as mBlindBoxCueCardRecord;
use Biz\model\brandActivity\BlindBoxLottery as mBlindBoxLottery;
use Biz\model\brandActivity\BlindBoxPointTask as mBlindBoxPointTask;
use Biz\model\ShopFavorite;
use Biz\model\wiki\ObjRelateWiki as mObjRelateWiki;
use Biz\model\wiki\Wiki as mWiki;
use Biz\pockets\constInterface\BlindBoxConfig;
use Doraemon\model\Like as mLike;
use Doraemon\model\Photos;
use Doraemon\model\Photos as mPhotos;
use Doraemon\model\PicStickers;
use Doraemon\pockets\constInterface\DotPlotTag\DotPlotTagType;
use Doraemon\service\Creator\UserLevel3;
use Doraemon\service\Point;
use Doraemon\service\statSign\Basic as basicStatSign;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\LinkFormat;
use Doraemon\tools\PointConfig;
use Hhzbeads\Point\PointClient;

class BlindBox implements BlindBoxConfig
{

    const TASK_RELATE_TOPIC_ID = 518;
    const TASK_RELATE_TOPIC_START_TIME = 1613664000;//2021-02-19


    /**
     * 获取用户当前的盲盒
     * @param $uid
     * @param int $source
     * @return array
     */
    public static function getUserBox($uid, $source = self::SOURCE_BLIND_BOX)
    {
        $info = [];
        $canOpenBox = 0;
        $records = [];
        if ($uid) {
            $canOpenBox = self::canOpenBox($uid, $source);
            $records = mBlindBoxChangeRecord::selectByWhere(['uid' => $uid, 'addtime[>=]' => date('Y-m-d'), 'addtime[<]' => date('Y-m-d', strtotime('+1days')), 'ORDER' => ['id' => 'DESC']]);
        }
        $info['can_open_count'] = $canOpenBox;
        if ($records) {
            $record = array_shift($records);
            $info['box_id'] = ($record['new_box_id'] != 0) ? $record['new_box_id'] : $record['box_id'];
        } else {
            $boxMap = self::getBlindBox($uid);
            $info['box_id'] = array_rand($boxMap);
            $date = date('Ymd');
            if ($date >= 20210202 && $date < 20210205) {//盲盒联名活动-尾巴生活
                $info['box_id'] = 1;
            }
            if ($date < 20210227) {
                $randMap = [
                    1 => 1,
                    2 => 2,
                    6 => 6
                ];
                $info['box_id'] = array_rand($randMap);
            }
            if ($uid) {
                mBlindBoxChangeRecord::insertData(['uid' => $uid, 'box_id' => $info['box_id'], 'change_type' => mBlindBoxChangeRecord::CHANGE_TYPE_SYS, 'new_box_id' => $info['box_id']]);
            }
        }
        return $info;
    }

    public static function getCurrentBoxId($uid)
    {
        $boxId = 0;
        $records = mBlindBoxChangeRecord::selectByWhere(['uid' => $uid, 'addtime[>=]' => date('Y-m-d'), 'addtime[<]' => date('Y-m-d', strtotime('+1days')), 'ORDER' => ['id' => 'DESC']]);
        if ($records) {
            $record = array_shift($records);
            $boxId = $record['new_box_id'];
        }
        return $boxId;
    }

    /**
     * 更换盲盒
     * @param $uid
     * @param $boxId
     * @return array
     * @throws \Exception
     */
    public static function changeBox($uid, $boxId)
    {
        $canOpenNum = BlindBox::canOpenBox($uid);
        if ($canOpenNum <= 0) {
            throw new \Exception('明天再继续吧～');
        }
        $canChangeNum = BlindBox::canChangeBox($uid);
        if ($canChangeNum <= 0) {
            throw new \Exception('今天用完 2 次换盒子的机会了哦');
        }
        $newBoxId = self::getNewBoxId($uid, $boxId);
        if ($newBoxId) {
            //扣积分
            $point = self::CHANGE_BOX_POINT;
            $currPoint = Point::getPoint($uid);
            if ($currPoint < $point) {
                throw new \Exception('积分不足');
            }
            $res = mBlindBoxChangeRecord::insertData(['uid' => $uid, 'change_type' => mBlindBoxChangeRecord::CHANGE_TYPE_POINT, 'box_id' => $boxId, 'new_box_id' => $newBoxId]);
            if (!$res) {
                throw new \Exception('更换盲盒失败');
            }
            $request_id = $uid . '-' . $boxId . '-' . $newBoxId . '-' . date('Ymd') . '-' . PointConfig::POINT_TYPE_BLIND_BOX_CHANGE;
            //扣除积分
            PointClient::deductPoint($uid, $point, PointConfig::POINT_TYPE_BLIND_BOX_CHANGE, $request_id, 'community', json_encode(['date' => date('Y-m-d'), 'box_id' => $boxId, 'new_box_id' => $newBoxId]));
            //更换盲盒
        } else {
            throw new \Exception('今日已无法更换盲盒');
        }
        $canOpenCount = self::canOpenBox($uid);
        return ['box_id' => $newBoxId, 'can_open_count' => $canOpenCount];
    }

    public static function getNewBoxId($uid, $boxId)
    {
        $records = mBlindBoxChangeRecord::selectByWhere(['uid' => $uid, 'addtime[>=]' => date('Y-m-d'), 'addtime[<]' => date('Y-m-d', strtotime('+1days')), 'ORDER' => ['id' => 'DESC']]);
        $changedBoxIds = [];
        if ($records) {
            $changedBoxIds = array_column($records, 'box_id');
        }
        $changedBoxIds[] = $boxId;
        $boxMap = self::getBlindBox($uid);
        $allBoxIds = array_keys($boxMap);
        $canChangeBoxIds = [];
        foreach ($allBoxIds as $val) {
            if (!in_array($val, $changedBoxIds)) {
                $canChangeBoxIds[] = $val;
            }
        }
        $newBoxId = 0;
        if ($canChangeBoxIds) {
            $key = array_rand($canChangeBoxIds);
            $newBoxId = $canChangeBoxIds[$key];
        }
        //如果没有新的盲盒了，则用最后一次的盲盒id
        return $newBoxId ? $newBoxId : $boxId;
    }

    /**
     * @param $uid
     * @param false $isLottery 是否抽奖
     * @param int $boxId
     * @return array
     */
    public static function getPrizeList($uid, $isLottery = false)
    {
        //品牌奖品，空盒子，积分，提示卡，好好住补位奖品（实物，京东卡）
        //品牌的奖品，不足3个，用好好住补位奖品补齐（实物奖品，京东卡，优选使用价值更低的来补位）
        $now = time();
        $where = [
            'activity_state' => mBlindBoxActivity::ACTIVITY_STATE_PASS,
            'start_time[<=]' => $now,
            'end_time[>=]' => $now
        ];
        $boxId = $uid ? BlindBox::getCurrentBoxId($uid) : 0;
        $excludedPrizeArr = self::excludedPrizeIds($uid, $boxId);
        $activityArr = mBlindBoxActivity::selectByWhere($where);
        $brandIds = [];
        $brandActivityList = [];
        $hhzActivityList = [];
        $limitCardActivityList = [];
        $basicIds = [];
        foreach ($activityArr as $row) {
            $basicIds[] = $row['basic_id'];
            if ($row['brand_id']) {
                $brandActivityList[] = $row;
                $brandIds[] = $row['brand_id'];
            } else if ($row['prize_type'] == mBlindBoxActivity::PRIZE_TYPE_LIMIT_CARD) {
                $limitCardActivityList[] = $row;
            } else {
                $hhzActivityList[] = $row;
            }
        }
        $isFavList = [];
        if (!$isLottery) {
            $basicIds = array_unique(array_filter($basicIds));
            $taskArr = $uid ? mBlindBoxPointTask::selectByWhere(['uid' => $uid, 'obj_id' => $basicIds, 'task_type' => mBlindBoxPointTask::TASK_TYPE_FAVORITE_GOODS]) : [];
            foreach ($taskArr as $row) {
                $isFavList[$row['obj_id']] = 1;
            }
        }
        $wikiArr = $basicIds ? mWiki::selectByWhere(['basic_id' => $basicIds, 'is_default' => 1, 'is_official' => 1, 'status[!]' => mWiki::STATUS_DEL], ['id', 'basic_id']) : [];
        $basicSpu = [];
        foreach ($wikiArr as $row) {
            $basicSpu[$row['basic_id']] = $row['id'];
        }
        $activityList = [];
        if ($brandActivityList) {
            $sortPrice = array_column($brandActivityList, 'prize_price');
            array_multisort($sortPrice, SORT_DESC, $brandActivityList);//价值由高到低
            $activityList = array_merge($activityList, $brandActivityList);
        }
        if ($hhzActivityList && count($brandActivityList) < 3) {//品牌奖品不足3个，用好好住奖品补齐（价值由低到高）
            $num = 3 - count($brandActivityList);
            $sortPrice2 = array_column($hhzActivityList, 'prize_price');
            array_multisort($sortPrice2, SORT_ASC, $hhzActivityList);
            $hhzActivityList = array_slice($hhzActivityList, 0, $num);
            $activityList = array_merge($activityList, $hhzActivityList);
        }
        $activityList = array_merge($activityList, $limitCardActivityList);
        $activityIds = array_column($activityList, 'id');
        $prizeList = mBlindBoxActivityPrize::selectByWhere(['activity_id' => $activityIds, 'prize_state[!]' => mBlindBoxActivityPrize::PRIZE_STATE_DEL, 'ORDER' => ['id' => 'ASC']]);
        $limitCardPrizeList = [];
        $activityPrizeInfos = [];
        foreach ($prizeList as $row) {
            if ($row['prize_type'] == mBlindBoxActivityPrize::PRIZE_TYPE_LIMIT_CARD) {
                $limitCardPrizeList[$row['activity_id']][$row['id']] = $row;
            }
            if (!isset($activityPrizeInfos[$row['activity_id']])) {
                if ($isLottery) {
                    switch ($row['prize_type']) {
                        case mBlindBoxActivityPrize::PRIZE_TYPE_JD_CARD:
                            if ($row['prize_state'] == mBlindBoxActivityPrize::PRIZE_STATE_NORMAL) {
                                $activityPrizeInfos[$row['activity_id']] = $row;
                            }
                            break;
                        case mBlindBoxActivityPrize::PRIZE_TYPE_SHOP_COUPON:
                        case mBlindBoxActivityPrize::PRIZE_TYPE_GOOD_COUPON:
                            $activityPrizeInfos[$row['activity_id']] = $row;
                            break;
                        default:
                            $activityPrizeInfos[$row['activity_id']] = $row;
                            break;
                    }
                } else {
                    $activityPrizeInfos[$row['activity_id']] = $row;
                }
            }
        }
        //限定卡奖品，随机一个奖品
        foreach ($limitCardPrizeList as $activityId => $rows) {
            $keys = array_keys($rows);
            $key = array_rand($keys);
            $prizeId = $keys[$key];
            $activityPrizeInfos[$activityId] = $rows[$prizeId];
        }

        $brandIds = array_unique($brandIds);
        $brandInfos = Brand::getBrandListByIds4App($brandIds);
        $list = [];
        foreach ($activityList as $row) {
            $activityId = $row['id'];
            $today = date('Ymd');
            $endDay = date('Ymd', $row['end_time']);
            $lastDay = ($today == $endDay) ? true : false;
            $prizeInfo = isset($activityPrizeInfos[$activityId]) ? $activityPrizeInfos[$activityId] : [];
            if ($prizeInfo) {
                $isExclude = (in_array($row['id'], $excludedPrizeArr['activity_ids']) || in_array($prizeInfo['id'], $excludedPrizeArr['prize_ids'])) ? 1 : 0;
                $prizeValue = $prizeInfo['prize_value'];
                if ($isLottery) {
                    if ($row['prize_stock'] <= 0 || empty($row['prize_stock'])) {//抽奖，需要去掉没有库存的奖品
                        continue;
                    }
                } else if (in_array($prizeInfo['prize_type'], [mBlindBoxActivity::PRIZE_TYPE_SHOP_COUPON, mBlindBoxActivity::PRIZE_TYPE_GOOD_COUPON, mBlindBoxActivity::PRIZE_TYPE_JD_CARD])) {
                    $prizeValue = '';//非抽奖使用，不返回优惠券码，京东卡号信息
                }
                $date = date('Ymd');
                if ($date >= 20210202 && $date < 20210205 && $row['id'] == 143) {//盲盒联名活动-尾巴生活
                    $row['prize_price'] = "201";
                }
                $statSign = $row['basic_id'] ? basicStatSign::genStatSign(basicStatSign::MODULE_BLIND_BOX_PRIZE_LIST, [],
                    ['basic_id' => $row['basic_id'], 'prize_type' => $row['prize_type'], 'act_from' => 'blind_box']) : '';
                $info = [
                    'brand_id' => $row['brand_id'],
                    'prize_id' => $prizeInfo['id'],
                    'prize_type' => $row['prize_type'],
                    'prize_title' => $row['prize_title'],
                    'prize_value' => $prizeValue,
                    'prize_price' => $row['prize_price'],
                    'prize_img' => $row['prize_img'],
                    'basic_id' => $row['basic_id'],
                    'activity_id' => $row['id'],
                    'brand_info' => ($row['brand_id'] && isset($brandInfos[$row['brand_id']])) ? $brandInfos[$row['brand_id']] : null,
                    'is_exclude' => $isExclude,
                    'is_fav' => ($row['basic_id'] && isset($isFavList[$row['basic_id']]) && $isFavList[$row['basic_id']]) ? 1 : 0,
                    'statSign' => $statSign,
                    'last_day' => $lastDay
                ];
                if (in_array($info['prize_type'], [mBlindBoxActivityPrize::PRIZE_TYPE_GOODS, mBlindBoxActivityPrize::PRIZE_TYPE_GOOD_COUPON]) && $info['basic_id'] && isset($basicSpu[$info['basic_id']])) {
                    $info['wiki_id'] = $basicSpu[$info['basic_id']];
                }
                $list[$prizeInfo['id']] = $info;
            }
        }
        $pointValue = self::getPointValue();
        $list[self::POINT_BOX_PRIZE_ID] = [
            'prize_id' => self::POINT_BOX_PRIZE_ID,//-1,积分奖品id
            'prize_type' => mBlindBoxActivityPrize::PRIZE_TYPE_POINT,//11,积分
            'prize_title' => $pointValue . '积分',
            'prize_value' => $pointValue,
            'activity_id' => 0,
            'is_exclude' => $isExclude = in_array(self::POINT_BOX_PRIZE_ID, $excludedPrizeArr['prize_ids']) ? 1 : 0,
        ];
        $list[self::CUE_CARD_BOX_PRIZE_ID] = [
            'prize_id' => self::CUE_CARD_BOX_PRIZE_ID,//-2,提示卡奖品id
            'prize_type' => mBlindBoxActivityPrize::PRIZE_TYPE_CUE_CARD,//12，提示卡
            'prize_title' => '排除卡',
            'activity_id' => 0,
            'is_exclude' => in_array(self::CUE_CARD_BOX_PRIZE_ID, $excludedPrizeArr['prize_ids']) ? 1 : 0,
        ];
        $list[self::EMPTY_BOX_PRIZE_ID] = [
            'prize_id' => self::EMPTY_BOX_PRIZE_ID,//0,空盒子奖品id
            'prize_type' => mBlindBoxActivityPrize::PRIZE_TYPE_EMPTY_BOX,//0,空盒子
            'prize_title' => '空盒子',
            'activity_id' => 0,
            'is_exclude' => 0,
        ];
        if ($isLottery) {//过滤掉已排除掉掉奖品
            foreach ($list as $index => $row) {
                if ($row['is_exclude']) {
                    unset($list[$index]);
                }
            }
        }
        return $list;
    }

    public static function getTaskList($uid)
    {
        $list = [
            mBlindBoxPointTask::TASK_TYPE_SIGN_IN => [
                'task_type' => mBlindBoxPointTask::TASK_TYPE_SIGN_IN,
                'point' => self::TASK_SIGN_POINT,
                'task_status' => mBlindBoxPointTask::TASK_STATE_UN_START,//0:未开始任务 1：待领取积分 2：已完成
            ],
            mBlindBoxPointTask::TASK_TYPE_FAVORITE_GOODS => [
                'task_type' => mBlindBoxPointTask::TASK_TYPE_FAVORITE_GOODS,
                'point' => self::TASK_FAVORITE_GOODS_POINT,
                'task_status' => mBlindBoxPointTask::TASK_STATE_UN_START,//0:未开始任务 1：待领取积分 2：已完成
            ],
            mBlindBoxPointTask::TASK_TYPE_SHARE_GOODS => [
                'task_type' => mBlindBoxPointTask::TASK_TYPE_SHARE_GOODS,
                'point' => self::TASK_SHARE_GOODS_POINT,
                'task_status' => mBlindBoxPointTask::TASK_STATE_UN_START,//0:未开始任务 1：待领取积分 2：已完成
            ],
            mBlindBoxPointTask::TASK_TYPE_LIKE => [
                'task_type' => mBlindBoxPointTask::TASK_TYPE_LIKE,
                'point' => self::TASK_LIKE_POINT,
                'task_status' => mBlindBoxPointTask::TASK_STATE_UN_START,//0:未开始任务 1：待领取积分 2：已完成
            ],
            mBlindBoxPointTask::TASK_TYPE_RELATE_WIKI => [
                'task_type' => mBlindBoxPointTask::TASK_TYPE_RELATE_WIKI,
                'point' => self::TASK_RELATE_WIKI_POINT,
                'task_status' => mBlindBoxPointTask::TASK_STATE_UN_START,//0:未开始任务 1：待领取积分 2：已完成
            ],
            mBlindBoxPointTask::TASK_TYPE_FOLLOW_BRAND => [
                'task_type' => mBlindBoxPointTask::TASK_TYPE_FOLLOW_BRAND,
                'point' => self::TASK_FOLLOW_BRAND_POINT,
                'task_status' => mBlindBoxPointTask::TASK_STATE_UN_START,//0:未开始任务 1：待领取积分 2：已完成
            ],
            mBlindBoxPointTask::TASK_TYPE_RELATE_TOPIC => [
                'task_type' => mBlindBoxPointTask::TASK_TYPE_RELATE_TOPIC,
                'point' => self::TASK_RELATE_TOPIC,
                'task_status' => mBlindBoxPointTask::TASK_STATE_UN_START,//0:未开始任务 1：待领取积分 2：已完成
            ]
        ];
        if ($uid) {
            $start = date('Y-m-d');
            $end = date('Y-m-d H:i:s', strtotime($start) + 86399);
            $taskList = mBlindBoxPointTask::selectByWhere(['uid' => $uid, 'addtime[>=]' => $start, 'addtime[<=]' => $end]);
            $taskList = array_column($taskList, null, 'task_type');
            $finishedTypes = [];
            foreach ($taskList as $type => $row) {
                $list[$type]['task_status'] = $row['task_state'];
                $finishedTypes[] = $type;
            }
            $allTypes = array_keys($list);
            $unFinishedTypes = array_diff($allTypes, $finishedTypes);
            foreach ($unFinishedTypes as $type) {
                switch ($type) {
                    case mBlindBoxPointTask::TASK_TYPE_FAVORITE_GOODS:
                        $count = ShopFavorite::selectCountWhere(['uid' => $uid, 'obj_type' => ShopFavorite::TYPE_WIKI, 'add_time[>=]' => $start, 'add_time[<=]' => $end, 'status' => ShopFavorite::STATUS_NORMAL]);
                        if ($count && $count > 0) {
                            $list[mBlindBoxPointTask::TASK_TYPE_FAVORITE_GOODS]['task_status'] = mBlindBoxPointTask::TASK_STATE_WAIT_FINISH;
                        }
                        break;
                    case mBlindBoxPointTask::TASK_TYPE_LIKE:
                        $lastTime = mLike::getLastLikeTime($uid);
                        if ($lastTime && $lastTime >= strtotime($start) && $lastTime <= strtotime($end)) {
                            $list[mBlindBoxPointTask::TASK_TYPE_LIKE]['task_status'] = mBlindBoxPointTask::TASK_STATE_FINISHED;
                        }
                        break;
                    case mBlindBoxPointTask::TASK_TYPE_RELATE_WIKI:
                        $where = [
                            'uid' => $uid,
                            'status' => mObjRelateWiki::STATUS_NORMAL,
                            'obj_type' => [mObjRelateWiki::OBJ_TYPE_NOTE, mObjRelateWiki::OBJ_TYPE_BLANK, mObjRelateWiki::OBJ_TYPE_ARTICLE],
                            'addtime[>=]' => $start,
                            'addtime[<=]' => $end,
                        ];
                        $count = mObjRelateWiki::getCountByWhere($where);
                        if ($count && $count > 0) {
                            $list[mBlindBoxPointTask::TASK_TYPE_RELATE_WIKI]['task_status'] = mBlindBoxPointTask::TASK_STATE_WAIT_FINISH;
                        } else {
                            //查询用户有没有品牌点图标签
                            $hasBrandStickers = self::hasBrandStickers($uid);
                            $list[mBlindBoxPointTask::TASK_TYPE_RELATE_WIKI]['task_status'] = $hasBrandStickers ? mBlindBoxPointTask::TASK_STATE_WAIT_FINISH : mBlindBoxPointTask::TASK_STATE_UN_START;
                        }
                        break;
                }
            }
        }
        $list[mBlindBoxPointTask::TASK_TYPE_RELATE_TOPIC]['task_status'] = self::getRelateTopicTaskStatus($uid);
        return array_values($list);
    }

    public static function getRelateTopicTaskStatus($uid)
    {
        $taskStatus = mBlindBoxPointTask::TASK_STATE_UN_START;
        if ($uid) {
            $info = mBlindBoxPointTask::getByWhere(['uid' => $uid, 'task_type' => mBlindBoxPointTask::TASK_TYPE_RELATE_TOPIC]);
            if ($info && $info['task_state'] == mBlindBoxPointTask::TASK_STATE_FINISHED) {
                $taskStatus = mBlindBoxPointTask::TASK_STATE_FINISHED;
            } else {
                $topicId = self::TASK_RELATE_TOPIC_ID;
                $startTime = self::TASK_RELATE_TOPIC_START_TIME;
                $photoId = mPhotos::getNoteIdsByUid($uid, ['topic_activity_id' => $topicId, 'addtime[>=]' => $startTime]);
                if ($photoId) {
                    $taskStatus = mBlindBoxPointTask::TASK_STATE_WAIT_FINISH;
                }
            }
        }
        return $taskStatus;
    }

    private static function hasBrandStickers($uid)
    {
        $result = false;
        $where = [
            'status' => [Photos::STATUS_SUCCESS, Photos::STATUS_UNTREATED],
            'addtime[>=]' => strtotime(date('Y-m-d')),
            'addtime[<=]' => strtotime(date('Y-m-d')) + 86399
        ];
        $noteIds = Photos::getNoteIdsByUid($uid, $where);
        $stickers = $noteIds ? PicStickers::getStickersByNoteId($noteIds) : [];
        foreach ($stickers as $row) {
            $imgTags = $row['img_tags'] ? json_decode($row['img_tags'], true) : [];
            foreach ($imgTags as $tag) {
                if ($tag['tag_type'] == DotPlotTagType::TAG_TYPE_BRAND && $tag['tag_id']) {
                    $result = true;
                    break;
                }
            }
            if ($result) {
                break;
            }
        }
        return $result;
    }


    /**
     * 用户可以打开盲盒的数量
     * @param $uid
     * @return int|bool
     */
    public static function canOpenBox($uid, $source = self::SOURCE_BLIND_BOX)
    {
        //添加redis 计数
        $where = [
            'uid' => $uid,
            'change_type' => mBlindBoxChangeRecord::CHANGE_TYPE_OPEN_BOX,
            'addtime[>=]' => date('Y-m-d'),
            'addtime[<]' => date('Y-m-d', strtotime('+1days')),
            'source' => $source,
            'ORDER' => ['id' => 'DESC']
        ];
        $max = 0;
        switch ($source) {
            case self::SOURCE_BLIND_BOX:
                list($maxBox, $userMaxBox) = self::getUserEveryDayMaxBox($uid);
                $max = $userMaxBox;
                break;
            case self::SOURCE_H5_ACTIVITY:
                $max = self::USER_EVERY_DAY_MAX_BOX_FREE;
                break;
        }
        $records = mBlindBoxChangeRecord::selectByWhere($where);
        $recordsCount = !empty($records) ? count($records) : 0;
        $num = $max - $recordsCount;
        $num = ($num > 0) ? $num : 0;
        return $num;
    }

    /**
     * 用户可以更换盲盒的数量
     * @param $uid
     * @return int|bool
     */
    public static function canChangeBox($uid)
    {
        //添加redis 计数
        $records = mBlindBoxChangeRecord::selectByWhere(['uid' => $uid, 'change_type' => mBlindBoxChangeRecord::CHANGE_TYPE_POINT, 'addtime[>=]' => date('Y-m-d'), 'addtime[<]' => date('Y-m-d', strtotime('+1days')), 'ORDER' => ['id' => 'DESC']]);
        $recordsCount = !empty($records) ? count($records) : 0;
        $num = self::USER_EVERY_DAY_CHANGE_BOX - $recordsCount;
        $num = ($num > 0) ? $num : 0;
        return $num;
    }

    public static function getBrandGoodsActivity($brandId)
    {
        $result = [];
        $now = time();
        $where = [
            'activity_type' => mBlindBoxActivity::ACTIVITY_TYPE_BLIND_BOX,
            'prize_type' => [mBlindBoxActivity::PRIZE_TYPE_GOODS, mBlindBoxActivity::PRIZE_TYPE_GOOD_COUPON],
            'activity_state' => mBlindBoxActivity::ACTIVITY_STATE_PASS,
            'prize_stock[>]' => 0,
            'start_time[<=]' => $now,
            'end_time[>=]' => $now,
            'brand_id' => $brandId,
        ];
        $info = mBlindBoxActivity::getByWhere($where);
        if ($info) {
            $result = [
                'id' => $info['id'],
                'title' => '抽奖进行中，快来参加吧～',
                'prize_type' => $info['prize_type'],
                'prize_price' => $info['prize_price'],
                'prize_title' => $info['prize_title'],
                'prize_img' => $info['prize_img'],
                'link' => self::getBlindBoxUrl()
            ];
        }
        return $result;
    }

    public static function shareGoodsTask($uid)
    {
        $start = date('Y-m-d');
        $end = date('Y-m-d H:i:s', strtotime($start) + 86399);
        $where = [
            'uid' => $uid,
            'task_type' => mBlindBoxPointTask::TASK_TYPE_SHARE_GOODS,
            'addtime[>=]' => $start,
            'addtime[<=]' => $end,
        ];
        $list = mBlindBoxPointTask::selectByWhere($where);
        if (empty($list)) {
            mBlindBoxPointTask::insertData(['uid' => $uid, 'task_type' => mBlindBoxPointTask::TASK_TYPE_SHARE_GOODS, 'task_state' => mBlindBoxPointTask::TASK_STATE_WAIT_FINISH]);
        }
    }

    public static function excludedPrizeIds($uid, $boxId)
    {
        $result = ['activity_ids' => [], 'prize_ids' => []];
        if ($uid && $boxId) {
            $where = [
                'uid' => $uid,
                'addtime[>=]' => date('Y-m-d'),
                'addtime[<]' => date('Y-m-d', strtotime('+1days')),
                'card_type' => mBlindBoxCueCard::CARD_TYPE_EXCLUDE,
                'box_id' => $boxId,
                'ORDER' => ['addtime' => 'DESC']
            ];
            $recordList = mBlindBoxCueCardRecord::selectByWhere($where);
            foreach ($recordList as $row) {
                $result['activity_ids'][] = $row['activity_id'];
                $result['prize_ids'][] = $row['prize_id'];
            }
        }
        return $result;
    }

    public static function getBlindBoxUrl()
    {
        $link = Hhzurl::getDomain() . '/brand/blind-box?hhzjump=1';
        return LinkFormat::encryptionLink($link);
    }

    private static function getPointValue()
    {
        $where = [
            'prize_type' => mBlindBoxActivity::PRIZE_TYPE_POINT,
            'addtime[>=]' => date('Y-m-d'),
            'addtime[<]' => date('Y-m-d', strtotime('+1days')),
        ];
        $prizeValues = mBlindBoxLottery::selectByWhere($where, 'prize_value');
        $total = $prizeValues ? array_sum($prizeValues) : 0;
        if ($total < 8000) {
            $arr = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100];
        } else {
            $arr = [5, 10];
        }
        $index = array_rand($arr, 1);
        return $arr[$index];
    }

    /**
     * 用户今天是否打开过盲盒
     * @param $uid
     * @return int|bool
     */
    public static function hasOpenedBox($uid)
    {
        //添加redis 计数
        $records = mBlindBoxChangeRecord::selectByWhere(['uid' => $uid, 'change_type' => mBlindBoxChangeRecord::CHANGE_TYPE_OPEN_BOX, 'addtime[>=]' => date('Y-m-d'), 'addtime[<]' => date('Y-m-d', strtotime('+1days')), 'ORDER' => ['id' => 'DESC']]);
        return !empty($records) ? true : false;
    }

    public static function getBlindBox($uid)
    {
        $result = [];
        $arr = self::BLIND_BOX_MAP;
        list($maxBox, $userMaxBox) = self::getUserEveryDayMaxBox($uid);
        //$date = date('Ymd');
        foreach ($arr as $boxId => $row) {
            if ($boxId <= $maxBox) {
                $result[$boxId] = [
                    'box_id' => $boxId,
                    'icon' => $row['icon']
                ];
            }
//            if ($date < 20210227 && isset($row['icon_activity']) && $row['icon_activity']) {//2021开工利是活动
//                $result[$boxId] = [
//                    'box_id' => $boxId,
//                    'icon' => $row['icon_activity']
//                ];
//            } else if (isset($row['icon']) && $row['icon']) {
//                $result[$boxId] = [
//                    'box_id' => $boxId,
//                    'icon' => $row['icon']
//                ];
//            }
        }
        return $result;
    }

    /**
     * 批量加分
     * @param $params
     */
    public static function addScore($params)
    {
        $uid = $params['uid']; //用户id
        $new_ids = $params['new_ids']; //obj_id集合
        $point = $params['point']; //任务领取的积分数
        $task_type = $params['task_type']; //任务类型（1：每日签到2：收藏1个商品3：分享一个商品4：点赞5：发布一条绑定商品的内容 11:关注品牌）
        $task_state = $params['task_state']; //任务状态（1:待领取积分2:已完成）
        $event_name = $params['event_name'];
        $result = false;
        //加分操作
        $data = [];
        //加积分
        foreach ($new_ids as $id) {
            $request_id = $uid . '-' . $id . '-' . $event_name;
            if ($params['type'] == 2) {
                $data['basic_id'] = $id;
            }
            $data['date'] = date('Y-m-d');
            $data['uid'] = $uid;
            PointClient::awardPoint($uid, $point, $event_name, $request_id, 'community', json_encode($data));
            $insertData = [
                'uid' => $uid,
                'obj_id' => $id,
                'task_type' => $task_type,
                'point' => $point,
                'task_state' => $task_state
            ];
            mBlindBoxPointTask::insertData($insertData);
        }
        $result = true;

        return $result;
    }

    private static function getUserEveryDayMaxBox($uid)
    {
        $userMaxBox = self::USER_EVERY_DAY_MAX_BOX;
        $maxBox = self::MAX_BOX;
        $levelInfo = UserLevel3::getLevelInfoByUid($uid);
        $userLevel = $levelInfo['user_level']; // 数字 1、2、3、 大于等于3 每日盲盒抽奖次数+1
        //如果用户生产等级是L3以上，增加一次盲盒抽奖机会
        if ($userLevel >= 3) {
            $userMaxBox = $userMaxBox + 1;
            $userMaxBox = ($userMaxBox <= self::USER_EVERY_DAY_MAX_BOX + 1) ? $userMaxBox : self::USER_EVERY_DAY_MAX_BOX + 1;
            $maxBox = $maxBox + 1;
            $maxBox = ($maxBox <= self::MAX_BOX + 1) ? $maxBox : self::MAX_BOX + 1;
        }
        return [$maxBox, $userMaxBox];
    }
}
